//
//  HEUploadCaseViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/6/18.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEUploadCaseViewController.h"
#import "HEOrderTitleCell.h"
#import "HEAddPhotoCell.h"
#import "HEUploadUtils.h"
#import "HECaseTypeCell.h"
#import "HEHealthHisItemModel.h"

@interface HEUploadCaseViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) UIButton *bottomView;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, assign) CGFloat topHeight;
@property (nonatomic, strong) NSMutableArray *videoUrls;
@property (nonatomic, strong) GDFiterCellModel *zzModel;
@property (nonatomic, strong) NSMutableArray *categDataSource;
@property (nonatomic, strong) NSString *titles;

@end

@implementation HEUploadCaseViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的病历";
     
    [self initUI];
    [self initCell];
    [self initTabBarView];
}

- (void)initNoticeTopView {
    
    NSString *nstr = @"您可以长按右侧话筒图标，在震动之后即可对输入框进行语音输入~上传视频资料时，您可选择或录制2个不超过30秒的视频文件";
    _topHeight = [nstr heightForFont:DYFont(16) width:KScreenWidth-30] + 30;
    UIView *noticeWarp = [[UIView alloc] initWithFrame: CGRectMake(0, ZXNavBarHeight, KScreenWidth, _topHeight )];
    noticeWarp.backgroundColor = KHexColor(@"E8F2FE");
    [self.view addSubview:noticeWarp];
 
    UILabel *noticeLb = [UILabel new];
    noticeLb.text = nstr;
    noticeLb.textColor = CNavBgColor;
    noticeLb.numberOfLines = 0;
    noticeLb.font = DYFont(16);
    [noticeWarp addSubview:noticeLb];
    
    [noticeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(noticeWarp).mas_offset(10);
        make.left.equalTo(noticeWarp).mas_offset(15);
        make.right.equalTo(noticeWarp).mas_offset(-15);
        make.bottom.equalTo(noticeWarp).mas_offset(-10);
    }];
}

- (void)initUI {
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - ZXSafeAreaBottom - 49) style:UITableViewStyleGrouped];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
   NSMutableArray *classArr = [NSMutableArray array];
   
    // 病例资料
    GDFiterCellModel *blTitleModel = [GDFiterCellModel new];
    blTitleModel.cellKlass = HEOrderTitleCell.class;
    blTitleModel.leftTitle = @"病历资料图片";
    blTitleModel.cellType = GDFiterCellTypeDoctorOrderHead;
    
    // 上传照片
    GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HEAddPhotoCell.class;
    photoModel.cellType = GDFiterCellTypeSelect_ADDPHOTO;
    photoModel.lineNum = 3;
    photoModel.photoMangeType = GDCellPhotoManagerSelectedTypePhoto;

    
    // 资料分类
    GDFiterCellModel *cateModel = [GDFiterCellModel new];
    cateModel.cellKlass = HEOrderTitleCell.class;
    cateModel.leftTitle = @"资料分类(可多选)";
    cateModel.cellType = GDFiterCellTypeDoctorOrderHead;
    
    // 多选
    GDFiterCellModel *typeModel = [GDFiterCellModel new];
    typeModel.cellKlass = HECaseTypeCell.class;
     
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[blTitleModel, photoModel, typeModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
     
    
    NSArray *sec1 = @[blTitleModel, photoModel];
    [_sections addObject: sec1];

    _categDataSource = @[].mutableCopy;
    NSArray *typeArr = @[@"出院诊断书", @"就诊记录", @"出院小结", @"出院记录", @"收费记录"];
    for(NSString *str in typeArr) {
        HEHealthHisItemModel *model = [HEHealthHisItemModel new];
        model.title = str;
        [_categDataSource addObject:model];
    }
    NSArray *categSections = @[_categDataSource];

    typeModel.cellData = categSections;
    NSArray *sec2 = @[cateModel, typeModel];
    [_sections addObject: sec2];

    [_tableView reloadData];
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView setTitle:@"提 交" forState:UIControlStateNormal];

    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

#pragma mark - load data

#pragma mark -
- (void)submit {

    if (self.formModel.cm_imgs.count == 0) {
        [Dialog toastBottom:@"请选择病历图片"];
        return;
    }
    self.titles = @"";
    NSMutableArray *titlArr = @[].mutableCopy;
    for (HEHealthHisItemModel *model in _categDataSource) {
        if (model.isSelect) {
            [titlArr addObject:model.title];
        }
    }
    
    if (titlArr.count == 0) {
        [Dialog toastBottom:@"请资料分类"];
        return;
    }
    self.titles = [titlArr componentsJoinedByString:@","];
  
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        // 上传图片
        [self uploadImage: self.formModel];
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self createSubmitRequest];
        });
    });
}

- (void)createSubmitRequest {
    HECommonRequest *request = [HECommonRequest new];
    request.service = @"savePhrUserCase";
    [request addParmas:self.titles key:@"case_name"];
    [request addParmas:[self.formModel.cm_imgUrls componentsJoinedByString:@","] key:@"case_photo"];
    [request addParmas: _usid key:@"usid"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KReportData parameters:request success:^(id  _Nonnull responseObject) {
 
        HECommonResponse *response = [HECommonResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"提交成功"];
            if (self.backBlock) {
                self.backBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)uploadImage:(GDFormModel *)model {
    dispatch_group_enter(_group);
    model.cm_imgUrls = @[].mutableCopy;

    if (!(model.cm_imgs.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images:model.cm_imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        

    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];

        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [model.cm_imgUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

  

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSMutableArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];

    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.proxyVC = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    if ( fiterModel.cellType == GDFiterCellTypeSelect_ADDPHOTO) {
        return fiterModel.cellHeight;
    }
 
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView *v = [[UIView alloc] init];
//    v.backgroundColor = CViewBgColor;
//    return v;
//}
 

#pragma mark - UITableViewDelegate
   
@end
